<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"   prefix="c" %>
<%@ page   import="grupobbva.pe.operhc.domain.SegUsuario"%>
<%@ page   import="java.util.List"%>
<%@page import="grupobbva.pe.operhc.util.Constant"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<%
String versionApp=(String)request.getSession().getAttribute(Constant.VERSIONAPP_SESSION);
%>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" media="screen" href="<%=request.getContextPath()%>/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="<%=request.getContextPath()%>/css/redmond/jquery-ui-1.8.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="<%=request.getContextPath()%>/css/operhc_style.css" />
<link rel="stylesheet" type="text/css" media="screen" href="<%=request.getContextPath()%>/css/buttonOHC.css" />

<script type="text/javascript" src='<%= request.getContextPath()%>/dwr/interface/SubCanalAction.js'></script>
<script type='text/javascript' src='<%= request.getContextPath()%>/dwr/engine.js'></script>
<script type='text/javascript' src='<%= request.getContextPath()%>/dwr/util.js'></script>
<script src="<%=request.getContextPath()%>/js/util/gridUtil.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/jquery-1.7.1.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/i18n/grid.locale-es.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/jquery.jqGrid.src.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/grid.subgrid.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/js/util/encabezado.js?ver<%=versionApp%>" type="text/javascript"></script>

<script type="text/javascript" charset="UTF-8">

var lastSel = '';
var rutaContexto1 = location.pathname;
var rutaContexto2 = "<%=request.getContextPath()%>";
var rutaContexto  = rutaContexto1.substr(0, rutaContexto1.indexOf(rutaContexto2)) + rutaContexto2;

<%
SegUsuario usuarioSession = (SegUsuario)request.getSession().getAttribute("usuarioSession");
if(!"1".equals(usuarioSession.getAdmin())){ 
response.sendRedirect("operativizacion.jsp");
}%>

var myColNames  = ['','','Codigo', 'Descripcion'];
var myDataModel = [ {name : 'codCanal',			index : 'codCanal'			,	width : VAL_WIDTH.SMALL,	editable:true, editrules: {edithidden:true, required:true}, hidden:true	},
                    {name : 'codSubCanalHdn',	index : 'codSubCanalHdn'	,	width : VAL_WIDTH.SMALL,	editable:true, editrules: {edithidden:true, required:true}, hidden:true	},
                    {name : 'codSubCanal',		index : 'codSubCanal'		,	width : VAL_WIDTH.SMALL,	editable:true, edittype:'text', editoptions: {size:23, maxlength: 2}, editrules: {required: true, integer: true, minValue: 1}},
                    {name : 'desSubCanal',		index : 'desSubCanal'		,	width : VAL_WIDTH.MED,		editable:true, edittype:'text', editoptions: {size:40, maxlength: 100}, editrules: {required: true}}                              
                   ];

if (jQuery.browser.msie){
	document.getElementsByName = function(name, tag){
	    return getElementsByName_iefix(name, tag);
	};
}

//frk: si damos agregar y luego ESC se debe eliminar la fila agregada
$(document).keyup(function(e) {
  //frk: se presiono el ESC
  var tecla = (document.all) ? e.keyCode : e.which; 
  if (tecla == 27) {
	  lastSel = '';
	  deleteTblRowAdded('listSubCanales');
  }
});

function consultar(operation, message){

	var formulario = document.getElementById('formSubCanalList');
	var codCanal = formulario.codCanal.value;
	
	jQuery("#listSubCanales").GridUnload();
	SubCanalAction.consultarAjax(codCanal, function(data){
		mostrarTabla(data);
		if(operation == 'logicDelete'){
			alert(message);
		}
	});
}

function mostrarTabla(data){
	
	var idTableForm = 'listSubCanales';
	$('body').append('<div id="paginador_listSubCanales" class="grid"></div>'); 
	var paginador = "paginador_listSubCanales";
	
	jQuery("#"+idTableForm).jqGrid(
	{
		beforeSelectRow: function(){},
		afterInsertRow: function(id, rowdata, rowelem){
			
			if(id == undefined){
				jQuery("#"+idTableForm).jqGrid('editRow', id,
		        { 
	       		    keys : true,
	       		    restoreAfterError : true,
	       		    errorfunc: function(rowid, response) {
	       		    	
	      		    	var mensaje = response.responseText;
	      		    	deleteTblRowAdded(idTableForm);
	      		    	
	   		    		if (mensaje != "" && mensaje != undefined) {
	   		    			setTimeout("alert('"+mensaje+"','Cerrar',{left:460})", 250);        		    			
  		    		    }else{
  		    		    	setTimeout("alert('Ocurrió un error al intentar guardar la información.','Cerrar',{left:460})", 250);
  		    		    }   		    		
	       		    },
	       		    afterrestorefunc: function(rowid) {
	       		    	lastSel = '';
	       		    },
	       		    aftersavefunc: function(rowid, response){
	       		    	lastSel = '';
	       		    	flushTblRowAdded(idTableForm, '', 3, 2, '');
	       		    }
	       		});
			}		
		},
		ondblClickRow: function(id, indexRow, indexCol, e){
			
			if(id && id!==lastSel){
				
				if(lastSel != ''){
		        	jQuery('#'+idTableForm).restoreRow(lastSel,true);
		        }
				
		        var codSubCanal = document.getElementsByName("codSubCanal")[0];
		    	var desCanal = document.getElementsByName("desCanal")[0];
		    	
		    	if(codSubCanal != undefined && desCanal != undefined){
		    		if($.trim(codSubCanal.value) == '' || $.trim(desCanal.value) == ''){
		    			
		    			deleteTblRowAdded(idTableForm);
		    			jQuery('#'+idTableForm).jqGrid('editRow',id,
    			        { 
    	        		    keys : true,
    	        		    restoreAfterError : true,
    	        		    errorfunc: function(rowid, response) {
    	        		    	
    	       		    		var mensaje = response.responseText;
    	    		    		if (mensaje != "" && mensaje != undefined) {
    	    		    			setTimeout("alert('"+mensaje+"','Cerrar',{left:460})", 250);        		    			
    	   		    		    }else{
    	   		    		    	setTimeout("alert('Ocurrió un error al intentar guardar la información.','Cerrar',{left:460})", 250);
    	   		    		    }
    	        		    },
    	        		    afterrestorefunc: function(rowid) {
    	        		    	lastSel = '';
    	        		    },
    	        		    aftersavefunc: function(rowid, response){
    	        		    	lastSel = '';
    	        		    }
    	        		});
    			        
    			        lastSel=id;
    			        if(lastSel == 'undefined'){
    			        	lastSel = '';
    			        }    			        
		    			        
		    		}else{
		    			jQuery("#"+idTableForm).jqGrid('saveRow', "undefined",
		    			{
			       		    restoreAfterError : false,
			       		    errorfunc: function(rowid, response) {
			       		    	
			      		    	var mensaje = response.responseText;
			      		    	deleteTblRowAdded(idTableForm);
			      		    	
			   		    		if (mensaje != "" && mensaje != undefined) {
			   		    			setTimeout("alert('"+mensaje+"','Cerrar',{left:460})", 250);        		    			
		  		    		    }else{
		  		    		    	setTimeout("alert('Ocurrió un error al intentar guardar la información.','Cerrar',{left:460})", 250);
		  		    		    }   		    		
			       		    },
			       		    aftersavefunc: function(rowid, response){
			       		    	lastSel = '';
			       		    	flushTblRowAdded(idTableForm, '', 3, 2, '');
			       		    }
			       		});
		    		}			        
		    	}else{
		    		
		    		jQuery('#'+idTableForm).jqGrid('editRow',id,
    		        { 
            		    keys : true,
            		    restoreAfterError : true,
            		    errorfunc: function(rowid, response) {
            		    	
           		    		var mensaje = response.responseText;
        		    		if (mensaje != "" && mensaje != undefined) {
        		    			setTimeout("alert('"+mensaje+"','Cerrar',{left:460})", 250);        		    			
       		    		    }else{
       		    		    	setTimeout("alert('Ocurrió un error al intentar guardar la información.','Cerrar',{left:460})", 250);
       		    		    }
            		    },
            		    afterrestorefunc: function(rowid) {
            		    	lastSel = '';
            		    },
            		    aftersavefunc: function(rowid, response){
            		    	lastSel = '';
            		    }
            		});
    		        
    		        lastSel=id;
    		        if(lastSel == 'undefined'){
			        	lastSel = '';
			        }
		    	}
		    }
		},
		onPaging: function(pgButton) {
			deleteTblRowAdded(idTableForm);
        },
		editurl		: rutaContexto+'/mantenimientoSubCanal.do?method=guardarSubCanalAjax',
	    caption		: "Listado de SubCanales",
		data 	 	: data,
		datatype 	: "local",
		height   	: "100%",
		weight 	 	: 1000,
		colNames 	: myColNames,
		colModel 	: myDataModel,
		rowList 	: [5,10,15,20,25],
		rowNum 		: 15, 
		pager 		: paginador,
		viewrecords : true,
		loadonce	: true,
		multiselect : true,			
		subGrid    	: false,
		footerrow  	: false,
		loadComplete :
           function (data) {}
	});
}

function deleteSubCanal(){
	
	var formulario = document.getElementById('formSubCanalList');
	var codCanalPadre = formulario.codCanal.value;
	
	var selecciones = buscarSelecciones("listSubCanales");
	if (selecciones.length == 0){
		alert('No ha seleccionado ningún elemento para la eliminación.');
	}else{
		
		var ans = confirm('¿Esta seguro que desea eliminar los registros seleccionados?');
		if(ans){
			
			SubCanalAction.eliminarSubCanalAjax(selecciones, codCanalPadre, function(msg){
				
				var paramDelete = '';
				if(msg != ''){
					paramDelete = 'logicDelete';
				}
				
				consultar(paramDelete, msg);
			});
		}
	}
}

function addSubCanal(){
	
	var formulario = document.getElementById('formSubCanalList');
	var codCanalPadre = formulario.codCanal.value;
	
	var rowid = "-1";
	var mydataadd = 
		  [{
			codCanal: codCanalPadre,
			codSubCanalHdn: rowid,
			codSubCanal  : "",
			desSubCanal  : ""
		  }];
	
	if(lastSel != ''){
		jQuery('#listSubCanales').restoreRow(lastSel,true);
	}
	
	lastSel = '';
	
	var codSubCanal = $("#undefined_codSubCanal");
	if(codSubCanal.length == 0){
		jQuery("#listSubCanales").addRowData(rowid, mydataadd, 'first');
	}
}

function backSubCanal(){
	
	var formulario = document.getElementById('formSubCanalList');
	formulario.action = rutaContexto+'/mantenimientoCanal.do?method=verListado';
	formulario.submit();
}

</script>

<body onload="consultar('','');">

<html:form method="post" styleId="formSubCanalList" action="mantenimientoSubCanal.do?method=verListado">
<html:hidden property="seleccionados" styleId="seleccionados"/>
<html:hidden property="codCanal" value="${command.codCanal}" styleId="codCanal"/>
<html:hidden property="desCanal" value="${command.desCanal}" styleId="desCanal"/>

	<div style="background-color: #0066bb;">
		<font face="Arial Narrow" size=3 color="#FFFFFF"><b>&nbsp;<bean:message key="etiqueta.titleManteSubCanal"/></b></font>
	</div>
	
	<center>
	<%
	Object messageError = request.getAttribute("messageError");
	if(messageError != null){
		if(messageError instanceof List){
			
			List listMsg = (List)messageError;
			if(!listMsg.isEmpty()){%>
				
				<div class="error">
					<% 
					for(int i = 0; i < listMsg.size(); i++){%>
						<img alt="" src="images/icono_error.png" width="17px" height="17px" class="icon">
			    		<%=listMsg.get(i)%><br/>
					<%}
					%>	
				</div>
			<%}			
			
		}else{
			if(!"".equals(messageError)){%>
				
				<div class="error">
			    	<img alt="" src="images/icono_error.png" width="17px" height="17px" class="icon">
			    	<%=messageError%><br/>
			    </div>				
			<%}
		}
	}
	%>
	

	<%
	Object messageInfo = request.getAttribute("messageInfo");
	if(messageInfo != null){
		if(messageInfo instanceof List){
			
			List listMsg = (List)messageInfo;
			if(!listMsg.isEmpty()){%>
				
				<div class="message">
					<% 
					for(int i = 0; i < listMsg.size(); i++){%>
						<img alt="" src="images/information-icon.png" width="17px" height="17px" class="icon">
			    		<%=listMsg.get(i)%><br/>
					<%}
					%>	
				</div>
			<%}			
			
		}else{
			if(!"".equals(messageInfo)){%>
				
				<div class="message">
			    	<img alt="" src="images/information-icon.png" width="17px" height="17px" class="icon">
			    	<%=messageInfo%><br/>
			    </div>				
			<%}
		}
	}
	%>
	</center>
	
	<br/>
	<table width="100%">
		<tr>
		<td align="center" valign="middle">
			
			<font face="Arial Narrow" size=3 color="#000080"><b>Configuración de SubCanales</b><BR>
			Canal <c:out value="${command.codCanal}"/>: <c:out value="${command.desCanal}"/>
			</font><br><br>
		
			<%--
			<html:button property="btnCrear" value="Crear" onclick="addSubCanal()" />&nbsp;&nbsp;
			<html:button property="btnEliminar" value="Eliminar" onclick="deleteSubCanal()" />&nbsp;&nbsp;
			<html:button property="btnCancelar" value="Cancelar" onclick="backSubCanal()" />
			 --%>
			 
			<a href="#" onclick="addSubCanal();" class="buttonOHC">CREAR</a>&nbsp;&nbsp;
			<a href="#" onclick="deleteSubCanal();" class="buttonOHC">ELIMINAR</a>&nbsp;&nbsp;
			<a href="#" onclick="backSubCanal();" class="buttonOHC">CANCELAR</a>
			
		</td>
		</tr>
	</table>
	<p></p>

	<center>
	<table id="listSubCanales" class="grid">
	</table>
	</center>
	

</html:form>
</body>
</html>